package com.ljf.tijian.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ljf.tijian.dto.ApiResponse;
import com.ljf.tijian.pojo.Doctor;
import com.ljf.tijian.service.DocterService;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
public class DocterController {

    @Autowired
    DocterService docterService;

    @PostMapping("/login")
    public ApiResponse login(@RequestBody Doctor doctor, HttpServletResponse response) throws JsonProcessingException {

        String docCode = doctor.getDocCode();
        String password = doctor.getPassword();
        System.out.println("login接口接收的参数为 docCode: "+docCode+",password: "+password);
//        return userService.login(user);
        ApiResponse apiResponse = docterService.login(doctor);
        Doctor doctors = (Doctor) apiResponse.getData();
        if(apiResponse.getStatus() == 200){
            Map<String,Object> map = new HashMap<>();
            map.put("currentUser",new ObjectMapper().writeValueAsString(doctors));

            JwtBuilder builder = Jwts.builder()
                    .setId(UUID.randomUUID().toString())
                    .setIssuedAt(new Date())
                    .setClaims(map).setSubject(doctor.getDocCode())
                    .signWith(SignatureAlgorithm.HS256,"123456---")
                    .setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 20))
                    ;

            String key = builder.compact();
            response.setHeader("token",key);
            System.out.println("返回JWT令牌");

            return apiResponse;
        }

        return apiResponse;
    }

}
